package malus.shaofeng.com.beiwomusic.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import malus.shaofeng.com.beiwomusic.MusicServer;
import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.model.NewStory;
import malus.shaofeng.com.beiwomusic.utils.BitmapHelper;
import malus.shaofeng.com.beiwomusic.utils.PlayTimeUtil;
import malus.shaofeng.com.beiwomusic.utils.Player;

public class MusicDetailActivity extends ActionBarActivity
        implements SeekBar.OnSeekBarChangeListener, View.OnClickListener, ServiceConnection {

    private MusicServer.MyController controller;
    private AudioManager audioManager;
    private NewStory storyExtra;
    private String path;
    private ImageView img_play;
    private boolean first;
    private TextView already_time;
    private TextView remain_time;
 //   private MusicServer musicServer;
    private SeekBar music_seekbar;
    private int currentPub;
    private int durationPub;
    private MusicReceive musicReceive;
    private Intent intent;
    private boolean isPlaying;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_detail);

        first = true;

        musicReceive = new MusicReceive();


        Intent intent = getIntent();
        storyExtra = (NewStory) intent.getSerializableExtra("storyExtra");
        path = storyExtra.getMusic().getHigh_url();

        TextView music_name = (TextView) findViewById(R.id.album_music_name);
        TextView artist_name = (TextView) findViewById(R.id.album_artist_name);

        already_time = (TextView) findViewById(R.id.already_play_time);
        remain_time = (TextView) findViewById(R.id.remain_play_time);

        music_name.setText(storyExtra.getMusic().getMusic_name());
        artist_name.setText(storyExtra.getMusic().getArtists().get(0).getArtist_name());

        ImageView album_img = (ImageView) findViewById(R.id.album_image);
        String image_uri = storyExtra.getMusic().getAlbum().getImage_uri();
        if (image_uri!=null){
            BitmapUtils bitmapUtils = BitmapHelper.getBitmapUtils();
            String imageUrl = BitmapHelper.getImageUrl(image_uri);
            bitmapUtils.display(album_img,imageUrl);
        }

        music_seekbar = (SeekBar) findViewById(R.id.album_seekBar);
        img_play = (ImageView) findViewById(R.id.album_btn_play);


        intent = new Intent("malus.shaofeng.com.beiwomusic.MUSIC_SERVICE");
        //   intent.setClass(MusicDetailActivity.this,MusicServer.class);
        startService(intent);
        bindService(intent,this,Context.BIND_AUTO_CREATE);

        img_play.setOnClickListener(this);
        music_seekbar.setOnSeekBarChangeListener(new SeekBarChangeEvent());

        SeekBar seekBarVolume = (SeekBar) findViewById(R.id.album_volume);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBarVolume.setMax(maxVolume);
        seekBarVolume.setProgress(currentVolume);
        seekBarVolume.setOnSeekBarChangeListener(this);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int seekBarProgress = seekBar.getProgress();
        if (seekBarProgress<1){
            seekBarProgress=1;
        }
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,seekBarProgress,0);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0,R.anim.trans_activity_out);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.album_btn_play) {

            if (controller==null)
                return;
            if (controller.isPlayed() && !controller.isMediaNull()) {
                img_play.setImageResource(R.drawable.article_song_play_normal);
                     controller.pause();
            } else if (!controller.isPlayed() && !controller.isMediaNull()){
                img_play.setImageResource(R.drawable.article_song_pause_normal);
                       controller.play();
            }
            if (first){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        controller.playUrl(path);
                    }
                }).start();
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("malus.shaofeng.com.beiwomusic.MUSIC_RECEIVE");
        registerReceiver(musicReceive,intentFilter);
    }

       @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
           controller=(MusicServer.MyController)service;
//        if (service!=null){
//            if (service instanceof MusicServer.MyController){
//                controller=(MusicServer.MyController)service;
//                musicServer = controller.getService();
//                musicServer.setOnProgressListener(new MusicServer.OnProgressListener() {
//                    @Override
//                    public void onProgress(int current, int duration) {
//                        currentPub = current;
//                        durationPub = duration;
//                        int remained = duration - current;
//                         if (duration >0){
//                            float pos = music_seekbar.getMax() * current / (duration *1.0f);
//                             music_seekbar.setProgress((int)pos);
//                            String currentPosition = PlayTimeUtil.calcTimeLenght(current);
//                            String remain = PlayTimeUtil.calcTimeLenght(remained);
//                            already_time.setText(currentPosition);
//                            remain_time.setText(remain);
//
//            }
//                    }
//                });
//            }
//        }
    }



    @Override
    public void onServiceDisconnected(ComponentName name) {
        controller=null;
    }

     class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress=progress*durationPub/seekBar.getMax();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
     //          musicServer.mediaPlayer.seekTo(progress);
            //    intent=new Intent();
              //     intent.putExtra("progress",progress);
            if ( !controller.isPlayed() || controller.isMediaNull()) {
                return;
            }

                controller.seekto(progress);
               already_time.setText(PlayTimeUtil.calcTimeLenght(currentPub));
               remain_time.setText(PlayTimeUtil.calcTimeLenght
                       (durationPub-currentPub));
        }
    }

//    @Override
//    protected void onDestroy() {
//        this.unbindService(this);
//        if (controller!=null){
//            controller.stop();
//        }
//        super.onDestroy();
//    }


    public class MusicReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String url = intent.getStringExtra("url");
            if (!url.equals(path))
                return;

            currentPub = intent.getIntExtra("serviceCurrent", 0);
            durationPub = intent.getIntExtra("serviceDuration", 0);
            isPlaying = intent.getBooleanExtra("isPlaying", false);

            int remained = durationPub - currentPub;
            if (durationPub > 0) {
                float pos = music_seekbar.getMax() * currentPub / (durationPub * 1.0f);
                music_seekbar.setProgress((int) pos);
                String currentPosition = PlayTimeUtil.calcTimeLenght(currentPub);
                String remain = PlayTimeUtil.calcTimeLenght(remained);
                already_time.setText(currentPosition);
                remain_time.setText(remain);

                if (!isPlaying) {
                    img_play.setImageResource(R.drawable.article_song_play_normal);
                } else {
                    img_play.setImageResource(R.drawable.article_song_pause_normal);
                }

            }
        }
    }

}
